import 'package:dio/dio.dart';
import 'package:json_annotation/json_annotation.dart';

import 'field_convert.dart';

part 'response.g.dart';

@JsonSerializable(createToJson: false, converters: nullFieldConvertList)
class ApiResponse<T> {
  ///  接口响应成功
  static const success = "1";

  /// 接口响应失败
  static const failed = "0";

  /// 账号在其它地方登录
  static const otherDeviceLogin = "2";

  /// 服务器错误码，具体参考[success]、[failed]、[otherDeviceLogin]
  String? code;

  /// 服务器返回响应描述
  String? msg;

  /// 服务器返回的数据
  @JsonKey(includeFromJson: false)
  T? data;

  /// 当[code] == [failed]时，用于判断具体的失败原因
  @JsonKey(includeFromJson: false)
  DioExceptionType? exceptionType;

  /// 分页总页码
  @DynamicToInt()
  int generalPage;

  /// 分页当前页码
  @DynamicToInt()
  int currentPage;

  ApiResponse(
      {this.code,
      this.msg,
      this.data,
      this.generalPage = 0,
      this.currentPage = 1,
      this.exceptionType});

  factory ApiResponse.fromJson(Map<String, dynamic> json,
      [T Function(dynamic json)? fromJsonT]) {
    var response = _$ApiResponseFromJson<T>(json);
    if (fromJsonT == null) {
      return response;
    }
    var dataJson = json['data'];
    response.data = dataJson != null ? fromJsonT(dataJson) : null;
    return response;
  }
}
